#include "../../../vcd-common-api/vcd-common.h"
#include "../../../vcd-common-api/vcd-log.h"
#include "../../vcd-message-dialog.h"
#include "../../vcd-start-window.h"
#include "../vcd-setting-window.h"
#include "vcd-xrandr.h"
#include "vcd-display.h"

extern GtkWidget *g_sys_set_window;
extern GtkWidget *g_snotebook;
extern GtkWidget *g_main_window;
GtkWidget *g_change_resolution_ask_window;

GtkWidget *g_fixed_vga_none;
char g_scr_cmd[100] = {0};//xrandr --output...
char g_del_which_mode[100];
char *g_old_mode = NULL;
#ifdef HAVE_XRANDR
DisOut* g_dis = NULL;
#endif
typedef struct
{
    GtkWidget *window;
    GtkWidget *entry_chang;
    GtkWidget *entry_kuan;
    GtkWidget *entry_fps;
} add_mode;
add_mode screen_data;

typedef struct
{
    GtkWidget *combo_display_interface;//display interface
    GtkWidget *combo_resolution;       //resolution
} sound_screen;
sound_screen sosc;

int screen_num = 0;

void change_screen_pic(GtkWidget *combo, GtkWidget *label);
void set_dpms_information(GtkWidget *combo);
void  write_dpms_tofile(int offtime);
void save_dpms(GtkWidget *button, GtkWidget *combo);
void del_xrandr_file(void);
void change_bright(GtkWidget *Scale);
int get_whether_dpms(void);
void add_mode_dialog(void);
void addmode(void);
void del_mode_dialog(void);
static void delete_mode(gpointer pt);
void buttonsetsosc(void);
char *get_jiekou(void);
char *get_screen1(int n);
#ifdef HAVE_XRANDR
void set_jiekou_information(DisOut* dis);
void set_screen_information(DisOut* dis);
#endif
char *get_current_mode(void);
void set_bright_information(GtkWidget *Scale);
void cb_change_resolution_buttonAsk(void);
void close_ask_window(void);
void dealwith_ok(void);
void set_old_mode(void);
void grade_init_dpms(void);



void set_bright_information(GtkWidget *Scale)
{
#ifdef __linux__
    if (access("/etc/X11/xinit/xinitrc.d/91-monitor-brightness.sh", F_OK) == -1){
        gtk_range_set_value((GtkRange *)Scale, 50);
    } else {
        char buf[10];
        FILE *pf = popen("cat /etc/X11/xinit/xinitrc.d/91-monitor-brightness.sh|awk '{printf $9}'", "r");
        fgets(buf, 10, pf);
        pclose(pf);
        gtk_range_set_value((GtkRange *)Scale, atof(buf) * 100 - 50);
    }
#endif
}

void set_old_mode(void)
{
#ifdef __linux__
    const char *vga = gtk_combo_box_text_get_active_text((GtkComboBoxText *)(sosc.combo_display_interface));
    char cmd[100] = {0};
    sprintf(cmd, "xrandr; xrandr --output %s --mode %s", vga, g_old_mode);
    int res = system(cmd);
    if (g_old_mode != NULL) {
        free(g_old_mode);
        g_old_mode = NULL;
    }
    if (res != 0) {
        LOG_ERROR("return g_old_mode error");
        return;
    }
//    gtk_widget_destroy(GTK_WIDGET(g_sys_set_window));
//    g_sys_set_window = NULL;
//    SysSetting();
//    gtk_notebook_set_current_page((GtkNotebook *)g_snotebook, 1);
//    gtk_window_set_position(GTK_WINDOW(g_main_window), GTK_WIN_POS_CENTER_ALWAYS);
//    gtk_window_set_position(GTK_WINDOW(g_sys_set_window), GTK_WIN_POS_CENTER_ALWAYS);
#endif
}

int get_whether_dpms(void)
{
    FILE *pf = NULL;
    char buf[100] = {0};
 #ifdef __linux__
    if (access("/etc/X11/xinit/xinitrc.d/50-disable-dpms.sh", F_OK) == -1) {
        LOG_ERROR("there is no 50-disable-dpms.sh file");
        return -1;
    }

    pf = popen("cat /etc/X11/xinit/xinitrc.d/50-disable-dpms.sh|grep dpms", "r");

    if (!fread(buf, 1, sizeof(buf), pf)) {
        LOG_ERROR("get whether close dpms error");
        return -1;
    }
#endif
    if (buf[5] == '-')
        return 0;
    else
        return 1;
}

void set_dpms_information(GtkWidget *combo)
{
    #ifdef __linux__
    int ret = get_whether_dpms();
    if (ret == 0) {
        gtk_combo_box_set_active(GTK_COMBO_BOX((GtkComboBox *)combo), 15);
        return;
    } else if (ret == -1) {
        M_DEBUG("file not found");
        return;
    }

    size_t si = 0;
    char* buff = exe_command("cat /etc/X11/xinit/xinitrc.d/50-disable-dpms.sh|grep dpms|awk '{print $3}'", &si);
    if (buff == NULL || si <= 0) {
        return;
    }

    const char* arr[]={"60", "120", "180",
                 "300", "600", "900",
                 "1200","1500","1800",
                 "2700","3600","7200",
                 "10800","14400","18000"};
    int i = 0;
    int count = sizeof(arr)/sizeof(arr[0]);
    for(i = 0; i < count; ++i){
        if(strcmp(buff, arr[i]) == 0){
            gtk_combo_box_set_active(GTK_COMBO_BOX((GtkComboBox *)combo), i);
            break;
        }
    }
    #endif
}

void  write_dpms_tofile(int offtime)
{
#ifdef __linux__
    FILE *new_dpms_file = NULL;
    if (offtime == 0) {
        system("xset -dpms");
        new_dpms_file = fopen("/etc/X11/xinit/xinitrc.d/50-disable-dpms.sh", "w");
        fputs("xset s off\nxset -dpms\n", new_dpms_file);
        fclose(new_dpms_file);
    } else {
        char cmd1[30];
        sprintf(cmd1, "xset dpms %d\n", offtime);
        system(cmd1);
        new_dpms_file = fopen("/etc/X11/xinit/xinitrc.d/50-disable-dpms.sh", "w");
        fputs("xset s off\n", new_dpms_file);
        fputs(cmd1, new_dpms_file);
        fclose(new_dpms_file);
    }
#endif
}

void save_dpms(GtkWidget *button, GtkWidget *combo)
{
    int num = gtk_combo_box_get_active((GtkComboBox *)combo);
    switch (num)
    {
        case 0:  write_dpms_tofile(60);    break;
        case 1:  write_dpms_tofile(120);   break;
        case 2:  write_dpms_tofile(180);   break;
        case 3:  write_dpms_tofile(300);   break;
        case 4:  write_dpms_tofile(600);   break;
        case 5:  write_dpms_tofile(900);   break;
        case 6:  write_dpms_tofile(1200);  break;
        case 7:  write_dpms_tofile(1500);  break;
        case 8:  write_dpms_tofile(1800);  break;
        case 9:  write_dpms_tofile(2700);  break;
        case 10: write_dpms_tofile(3600);  break;
        case 11: write_dpms_tofile(7200);  break;
        case 12: write_dpms_tofile(10800); break;
        case 13: write_dpms_tofile(14400); break;
        case 14: write_dpms_tofile(18000); break;
        case 15: write_dpms_tofile(0);     break;
        default: break;
    }
}

void del_xrandr_file(void)
{
    //const char *str = "delete xrandr file";
    //cb_button_ask((gpointer)str);
}

void change_bright(GtkWidget *Scale)
{
    #ifdef __linux__
    char bright_cmd[100] = {0};
    gdouble bright = gtk_range_get_value((GtkRange *)Scale);
    snprintf(bright_cmd,sizeof(bright_cmd), "xrandr --output $(xrandr|grep ' connected'|awk '{print $1}') --brightness %.2f\n", (double)(bright + 50) / 100);
    system(bright_cmd);

    FILE *pf = NULL;
    pf = fopen("/etc/X11/xinit/xinitrc.d/91-monitor-brightness.sh", "w");
    fputs(bright_cmd, pf);
    fclose(pf);
    #endif
}

void grade_init_dpms(void)
{
    GtkWidget *label_grade, *label_bright, *btn_quit, *btn_init, *fixed, *btnok, *fixed_screen, *fixed_bright, *init_label;
    GtkWidget *screenlabel, *separ_head, *ping_bao, *main_vbox, *fixed_init, *scale_dpms;
    GtkWidget *grade_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_keep_above(GTK_WINDOW(grade_window), TRUE);
    gtk_window_set_modal((GtkWindow *)grade_window, TRUE);
    gtk_window_set_position(GTK_WINDOW(grade_window), GTK_WIN_POS_CENTER_ALWAYS);//居中
    gtk_container_set_border_width(GTK_CONTAINER(grade_window), 5);
    gtk_window_set_decorated(GTK_WINDOW(grade_window), FALSE);

    separ_head = gtk_separator_new (GTK_ORIENTATION_HORIZONTAL);
    gtk_widget_set_size_request(separ_head, 410, 1);
    label_grade = gtk_label_new("高级");
    btn_quit = gtk_button_new_with_label("X");
    gtk_button_set_relief(GTK_BUTTON(btn_quit), GTK_RELIEF_NONE);
    gtk_widget_set_size_request(btn_quit, 30, 30);
    btn_init = gtk_button_new_with_label("清空");
    gtk_button_set_relief(GTK_BUTTON(btn_init), GTK_RELIEF_NONE);
    gtk_widget_set_size_request(btn_init, 100, 30);
    init_label  = gtk_label_new("清空自定义分辨率并重启");
    fixed_init = gtk_fixed_new();
    gtk_fixed_put((GtkFixed *)fixed_init, init_label, 0, 10);
    gtk_fixed_put((GtkFixed *)fixed_init, btn_init, 275, 0);

    btnok = gtk_button_new_with_label("保存");
    gtk_button_set_relief(GTK_BUTTON(btnok), GTK_RELIEF_NONE);
    gtk_widget_set_size_request(btnok, 100, 30);
    screenlabel = gtk_label_new("自动关闭屏幕");
    ping_bao = gtk_combo_box_text_new();
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "1分钟");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "2分钟");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "3分钟");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "5分钟");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "10分钟");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "15分钟");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "20分钟");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "25分钟");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "30分钟");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "45分钟");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "1小时");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "2小时");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "3小时");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "4小时");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "5小时");
    gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)ping_bao), NULL, "从不 ");
    gtk_widget_set_size_request(ping_bao, 105, 20);
    fixed_screen = gtk_fixed_new();
    gtk_fixed_put((GtkFixed *)fixed_screen, screenlabel, 0,   10);
    gtk_fixed_put((GtkFixed *)fixed_screen, ping_bao,    158, 0);
    gtk_fixed_put((GtkFixed *)fixed_screen, btnok,       275, 0);

    label_bright = gtk_label_new("屏幕亮度");
    fixed_bright = gtk_fixed_new();
    gtk_fixed_put((GtkFixed *)fixed_bright, label_bright, 0, 21);
    scale_dpms = gtk_scale_new_with_range(GTK_ORIENTATION_HORIZONTAL, 0, 100, 1);
    gtk_widget_set_size_request(scale_dpms, 280, 20);
    gtk_fixed_put((GtkFixed *)fixed_bright, scale_dpms, 100, 0);

    main_vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 10);
    gtk_container_set_border_width (GTK_CONTAINER (main_vbox), 16);
    gtk_box_pack_start (GTK_BOX (main_vbox), fixed_init,   TRUE, TRUE, 0);
    gtk_box_pack_start (GTK_BOX (main_vbox), fixed_screen, TRUE, TRUE, 0);
    gtk_box_pack_start (GTK_BOX (main_vbox), fixed_bright, TRUE, TRUE, 0);

    fixed = gtk_fixed_new();
    gtk_fixed_put((GtkFixed *)fixed, label_grade, 175, 8);
    gtk_fixed_put((GtkFixed *)fixed, btn_quit,    360, 0);
    gtk_fixed_put((GtkFixed *)fixed, separ_head,  0,   43);
    gtk_fixed_put((GtkFixed *)fixed, main_vbox,   0,   63);

    set_dpms_information(ping_bao);
    set_bright_information(scale_dpms);

    gtk_container_add(GTK_CONTAINER(grade_window), fixed);
    gtk_widget_show_all(grade_window);
    g_signal_connect(G_OBJECT(btn_init), "clicked", G_CALLBACK(del_xrandr_file), NULL);
    g_signal_connect(G_OBJECT(btnok), "clicked", G_CALLBACK(save_dpms), ping_bao);
    g_signal_connect_swapped(G_OBJECT(btn_quit), "clicked", G_CALLBACK(gtk_widget_destroy), grade_window);
    g_signal_connect(G_OBJECT(scale_dpms), "value_changed", G_CALLBACK(change_bright), NULL);
    set_css(btn_init, "button{ color:white;"
            "background:#5cb85c;border:1px solid rgb(57,132,57);"
            "border-radius:0px}");
    set_css(btn_init, "button:hover{background:#449d44;}");
    set_css(btnok, "button{ color:white;"
            "background:#5cb85c;border:1px solid rgb(57,132,57);"
            "border-radius:0px}");
    set_css(btnok, "button:hover{background:#449d44;}");
    set_css(grade_window, "window{ background-color:rgb(255,255,255);"
            "border-radius:0px}");
    set_css(btn_quit, "button{ border-radius:0px;}");
    set_css(btn_quit, "button:hover{ border-radius:0px;border:none;box-shadow:3px 3px 5px alpha(rgb(150,150,150),0.5) inset}");
    set_css(label_grade, "label{border-radius:0px}");
}

void change_screen_pic(GtkWidget *combo, GtkWidget *label)
{
    const char* vga = "1440x900";
    int width = 1440;
    int height = 900;
    char *tmp = gtk_combo_box_text_get_active_text((GtkComboBoxText *)combo);
    if (NULL != tmp) {
        vga = tmp;
    }

    int ret = sscanf(vga, "%dx%d", &width, &height);
    if (ret != 2) {
        return;
    }

    M_DEBUG("width:%d  height:%d vga:%s", width, height, vga);

    gtk_fixed_move((GtkFixed *)g_fixed_vga_none, label, 285 - (width / 40), 117 - (height / 40));
    gtk_widget_set_size_request(label, width / 20, height / 20);
}

void addmode(void)
{
    #ifdef __linux__
    int i, j, a;
    FILE *pf;
    char cmd_newmode[200]   = {0};//xrandr --newmode "mode_line后面的"
    char cmd_addmode[100]   = {0};//xrandr --addmode 400x400_75.00
    char new_add_mode[500] = {0};
    char res[400] = {0};
    const char *vga = gtk_combo_box_text_get_active_text((GtkComboBoxText *)(sosc.combo_display_interface));
    //输入cvt 400 400 75 得到以下
    //# 400x400 74.23 Hz (CVT) hsync: 31.25 kHz; pclk: 15.50 MHz
    //mode_line "400x400_75.00"   15.50  400 416 448 496  400 403 413 421 -hsync +vsync
    char res2[200] = {0};//得到的是mode_line后面的哪一行
    char res_mode[40] = {0};//存放newmode “400x400_75.00”*****************这句话已经变成全局变量了因为下面要用
    //add_mode *Data=data;
    const char *chang = gtk_entry_get_text(GTK_ENTRY(screen_data.entry_chang));
    const char *kuan  = gtk_entry_get_text(GTK_ENTRY(screen_data.entry_kuan));
    const char *fps   = gtk_entry_get_text(GTK_ENTRY(screen_data.entry_fps));

    if (!(is_digit(chang) && is_digit(kuan) && is_digit(fps))) {
        printf("%s,%s,%s is not digit\n", chang, kuan, fps);
        message_box("      非法分辨率！      ");
        return;
    }
    char cmd1[25] = {0};//cvt 400 400 75
    sprintf(cmd1, "cvt %s %s %s", chang, kuan, fps);

    pf = popen(cmd1, "r");

    if (!fread(res, 1, 400, pf)) {
        message_box("      创建新分辨率失败！      ");
    } else {
        for (i = 0; i < sizeof(res) - 5; i++) {
            if (res[i] == 'l' && res[i + 1] == 'i' && res[i + 2] == 'n' && res[i + 3] == 'e' && res[i + 4] == ' ') {
                for (j = 0; j < (sizeof(res) - i); j++) {
                    if (res[i + 5] == '\n')
                        continue;
                    res2[j] = res[i + 5]; //得到mode_line后面的内容
                    i++;
                }
            }
        }
        for (i = 0; i < sizeof(res2); i++) {
            if (res2[i] == ' ')
            {break;}
            else
            {res_mode[i] = res2[i];}
        }
        res_mode[i] = '\0';
        pclose(pf);

        strcat(cmd_newmode, "xrandr --newmode ");
        strcat(cmd_newmode, res2);
        int b = system(cmd_newmode);
        if (b != 0) {
            message_box("      创建新分辨率失败！      ");
        } else {
            strcat(cmd_addmode, "xrandr --addmode ");
            strcat(cmd_addmode, vga);
            strcat(cmd_addmode, " ");
            strcat(cmd_addmode, res_mode);

            gtk_widget_destroy(GTK_WIDGET(screen_data.window));//点击确定直接关闭本界面
            a = system(cmd_addmode);
            if (a == 0) {//如果这个命令执行成功则返回0若执行不成功则返回256，不成功杀也不用干
                FILE *fp = fopen("/etc/X11/xinit/xinitrc.d/90-monitor.sh", "a+");
                if (NULL == fp) {
                    printf("file open Fail!\n");
                }
                a = system("chmod 777 /etc/X11/xinit/xinitrc.d/90-monitor.sh");
                char ch = fgetc(fp);
                if (ch == EOF)
                    fputs("xrandr\n", fp);
                strcpy(new_add_mode, cmd_newmode);
                strcat(new_add_mode, ";");
                strcat(new_add_mode, cmd_addmode);
                fputs(new_add_mode, fp);
                fputs("\n", fp);
                fclose(fp);
            } else {
                message_box("        添加分辨率失败！        ");
            }
        }
    }
    #endif
}

void add_mode_dialog(void)
{
    GtkWidget *grid, *button_ok, *button_no, *hbox;
    screen_data.window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_modal((GtkWindow *)screen_data.window, TRUE);
    gtk_window_set_keep_above(GTK_WINDOW(screen_data.window), TRUE);
    gtk_window_set_position(GTK_WINDOW(screen_data.window), GTK_WIN_POS_CENTER_ALWAYS);//居中
    gtk_container_set_border_width(GTK_CONTAINER(screen_data.window), 35);
    gtk_window_set_decorated(GTK_WINDOW(screen_data.window), FALSE);//无边框

    grid = gtk_grid_new();

    button_ok = gtk_button_new_with_label("确定");
    button_no = gtk_button_new_with_label("取消");

    screen_data.entry_chang = gtk_entry_new();
    screen_data.entry_kuan  = gtk_entry_new();
    screen_data.entry_fps   = gtk_entry_new();

    hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 40);
    gtk_box_pack_start(GTK_BOX(hbox), button_ok, FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(hbox), button_no, FALSE, FALSE, 0);

    gtk_widget_set_size_request(screen_data.entry_chang, 240, 30);
    gtk_widget_set_size_request(screen_data.entry_kuan,  240, 30);
    gtk_widget_set_size_request(screen_data.entry_fps,   240, 30);
    gtk_widget_set_size_request(button_ok, 100, 30);
    gtk_widget_set_size_request(button_no, 100, 30);
    gtk_button_set_relief(GTK_BUTTON(button_ok), GTK_RELIEF_NONE);
    gtk_button_set_relief(GTK_BUTTON(button_no), GTK_RELIEF_NONE);

    gtk_grid_set_row_spacing((GtkGrid*)grid, 8);

    gtk_grid_attach((GtkGrid *)grid, screen_data.entry_chang, 0, 0, 1, 1);
    gtk_grid_attach((GtkGrid *)grid, screen_data.entry_kuan, 0, 1, 1, 1);
    gtk_grid_attach((GtkGrid *)grid, screen_data.entry_fps, 0, 2, 1, 1);
    gtk_grid_attach((GtkGrid *)grid, hbox, 0, 3, 1, 1);

    gtk_entry_set_placeholder_text(GTK_ENTRY(screen_data.entry_chang), "宽");
    gtk_entry_set_placeholder_text(GTK_ENTRY(screen_data.entry_kuan),  "高");
    gtk_entry_set_placeholder_text(GTK_ENTRY(screen_data.entry_fps),   "刷新频率");
    gtk_widget_set_can_focus(button_no, TRUE);
    gtk_widget_grab_focus(button_no);

    gtk_container_add(GTK_CONTAINER(screen_data.window), grid);

    g_signal_connect(G_OBJECT(button_ok), "clicked", G_CALLBACK(addmode), NULL);
    g_signal_connect_swapped(G_OBJECT(button_no), "clicked", G_CALLBACK(gtk_widget_destroy), screen_data.window);
    /*            CSS                  */
    set_css(button_ok, "button{color: white;background: rgb(53, 126, 169);border: 1px solid rgb(40, 94, 142);border-radius: 0px}");
    set_css(button_ok, "button:hover{border-radius:0px;background: #3070a9}");
    set_css(button_no, "button{color: white;background: #5cb85c;border: 1px solid rgb(57, 132, 57);border-radius: 0px}");
    set_css(button_no, "button:hover{border-radius:0px;background: #449d44;}");
    set_css(screen_data.window, "window{border-radius:0px;background-color: rgb(255, 255, 255)}");
    set_css(screen_data.entry_chang, "entry{background:rgb(255,255,255);border:1px solid rgb(204,204,204);border-radius:0px;padding-left:12px}");
    set_css(screen_data.entry_kuan, "entry{background:rgb(255,255,255);border:1px solid rgb(204,204,204);border-radius:0px;padding-left:12px}");
    set_css(screen_data.entry_fps, "entry{background:rgb(255,255,255);border:1px solid rgb(204,204,204);border-radius:0px;padding-left:12px}");
    /*            CSS                 */
    gtk_widget_show_all(screen_data.window);
}

static void delete_mode(gpointer pt)
{
    #ifdef __linux__
    int a;
    char cmd[200] = {0};
    const char *vga = gtk_combo_box_text_get_active_text((GtkComboBoxText *)(sosc.combo_display_interface));
    const char *reso = gtk_combo_box_text_get_active_text((GtkComboBoxText *)(sosc.combo_resolution));
    char delmode[200] = {0};
    snprintf(delmode,sizeof(delmode), "xrandr --delmode %s %s", vga,reso);
    a = system(delmode);
    printf("commond:%s\n", delmode);
    if (a == 0){
        message_box("          删除成功！          ");
        get_screenNum();
        sprintf(cmd, "sed -i '/%s \"%s\"/d' /etc/X11/xinit/xinitrc.d/90-monitor.sh", vga, g_del_which_mode);
        int res = system(cmd);
        if (res != 0){
            M_DEBUG("sed 90-monitor error");
        }
    }else{
        message_box("      删除分辨率失败！       ");
    }
    #endif
}

void del_mode_dialog(void)
{/*
    GtkWidget* top_win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    GtkWidget *dialog;
    dialog = gtk_message_dialog_new((GtkWindow*)top_win,
                GTK_DIALOG_DESTROY_WITH_PARENT,
                GTK_MESSAGE_QUESTION,
                GTK_BUTTONS_YES_NO,
                "Are you sure to delete?");
    gtk_window_set_title(GTK_WINDOW(dialog), "Question");
    GtkResponseType result =  gtk_dialog_run(GTK_DIALOG(dialog));
    switch(result){
    case GTK_RESPONSE_YES:
        printf("response yes\n");
        delete_mode();
        break;
    case GTK_RESPONSE_NO:
        printf("response no\n");
        break;
    default:
        printf("response %d\n", (int)result);
        break;
    }

    gtk_widget_destroy(top_win);
    */

    message_diag_context *t = g_malloc0(sizeof(message_diag_context));
    g_return_if_fail(t != NULL);
    t->btn_yes = delete_mode;
    t->btn_no = NULL;
    t->info = "是否确定删除此分辨率";
    t->user_data = NULL;
    vcd_message_dialog(t);
    g_free(t);
    t = NULL;
}

char *get_current_mode(void)
{

    char *mode_line = (char *)malloc(20 * sizeof(char *));
    #ifdef __linux__
    char mode[20] = {0};
    FILE *pf = popen("xrandr|grep '*'|awk '{print $1}'", "r");
    if (!fgets(mode, 20, pf))
    {
        LOG_ERROR("get current mode error");
        pclose(pf);
        return mode_line;
    }
    mode[strlen(mode) - 1] = 0;
    strcpy(mode_line, mode);
    pclose(pf);
    #endif
    return mode_line;
}

void buttonsetsosc(void)
{
#ifdef __linux__
    const char *vga = gtk_combo_box_text_get_active_text((GtkComboBoxText *)(sosc.combo_display_interface));
    gchar *scr = gtk_combo_box_text_get_active_text((GtkComboBoxText *)sosc.combo_resolution);
    g_old_mode = get_current_mode();

    strcpy(g_scr_cmd, "");
    sprintf(g_scr_cmd, "xrandr --output %s --mode %s", vga, scr);
    int ret = system(g_scr_cmd);
    if (ret == 0) {
        int res = system("/usr/bin/feh --bg-scale /etc/xdg/openbox/wallpaper.jpg");
        if (res != 0) {
            M_DEBUG("/usr/bin/feh --bg-scale /etc/xdg/openbox/wallpaper.jpg error");
        }
        gtk_window_set_position(GTK_WINDOW(g_start_window->main_window_handle), GTK_WIN_POS_CENTER_ALWAYS);
        gtk_window_set_position(GTK_WINDOW(g_sys_setting->sys_set_window), GTK_WIN_POS_CENTER_ALWAYS );
        cb_change_resolution_buttonAsk();
    } else {
        message_box("    应用失败,无效的分辨率！    ");
    }
#endif
}

char *get_jiekou(void)
{
    char *jiekou_last = (char *)malloc(30 * sizeof(char));
    #ifdef __linux__
    if (NULL == jiekou_last)
    {printf("malloc error");}
    strcpy(jiekou_last, "   ");
    FILE *pf;
    char res[20] = {0};
    pf = popen("xrandr|grep \" connected \"|awk '{print $1}'", "r");
    if (!fgets(res, 20, pf))
    {
        printf("get_jiekou error");
        pclose(pf);
        return jiekou_last;
    }
    strcat(jiekou_last, res);
    pclose(pf);
    jiekou_last[strlen(jiekou_last) - 1] = 0;
    #endif
    return jiekou_last;
}

char *get_screen1(int n)//显示一个分辨率
{
    char *line_buff = (char *)malloc(180 * sizeof(char));
    #ifdef __linux__
    if (NULL == line_buff)
    {printf("malloc error");}
    FILE *pf;
    pf = popen("xrandr|grep -A 100 \" connected \"", "r");
    int i;
    for (i = 0; i < n + 1; i++)
    {
        if (!fgets(line_buff, 180, pf))
        {
            M_DEBUG("get screen1 error");
            pclose(pf);
            return line_buff;
        }
    }
    strcpy(line_buff, "");
    if (!fgets(line_buff, 19, pf))
    {
        M_DEBUG("get screen1 error");
        pclose(pf);
        return line_buff;
    }

    if (line_buff[strlen(line_buff) - 1] == '0')
    {
        line_buff[strlen(line_buff)] = 0;
    } else
    {
        line_buff[strlen(line_buff) - 1] = ' ';
        line_buff[strlen(line_buff)]   = 0;
    }
    pclose(pf);
    #endif
    return line_buff;
}

#ifdef HAVE_XRANDR
void set_jiekou_information(DisOut* dis)
{
    if (dis == NULL || dis->noutput <= 0) {
        return;
    }

    gtk_combo_box_text_remove_all((GtkComboBoxText *)(sosc.combo_display_interface));

    int i = 0;
    for (; i < dis->noutput; ++i) {
        OutPut* p = dis->output + i;
        if (p->connected != OUTPUT_CONNECT_YES) {
            continue;
        }
        gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT((GtkComboBoxText *)sosc.combo_display_interface), NULL, p->name);
    }

    gtk_combo_box_set_active(GTK_COMBO_BOX((GtkComboBox *)sosc.combo_display_interface), 0);
}
#endif

gboolean get_screenNum(void)//得到分辨率的个数
{
    #ifdef HAVE_XRANDR
    if (g_dis) {
        destroy_dis_out(g_dis);
        g_dis = NULL;
    }

    DisOut* dis = get_dis_out();
    if (!dis) {
        LOG_ERROR("Can't open displayXOpen");
        message_box("分辨率显示异常，获取X11接口失败");
        return FALSE;
    } else {
        g_dis = dis;
    }

    set_jiekou_information(dis);
    set_screen_information(dis);
    #endif
    return FALSE;
}
#ifdef HAVE_XRANDR
void set_screen_information(DisOut* dis)
{
    int i = 0;
    OutPut *dst = NULL;
    const char *vga = gtk_combo_box_text_get_active_text((GtkComboBoxText *)(sosc.combo_display_interface));

    //find same name display interface
    for (i = 0; i < dis->noutput; ++i) {
        OutPut *p = dis->output + i;
        if (strcmp(p->name, vga) == 0) {
            dst = p;
            break;
        }
    }

    if (dst == NULL || dst->nmode <= 0) 
        return;

    char *current_mode = get_current_mode();
    gtk_combo_box_text_remove_all((GtkComboBoxText *)(sosc.combo_resolution));
    for (i = 0; i < dst->nmode && i < 20; ++i) {
        gtk_combo_box_text_append_text((GtkComboBoxText *)sosc.combo_resolution, dst->modes[i]);
    }
    
    gtk_combo_box_text_prepend_text((GtkComboBoxText *)sosc.combo_resolution, current_mode);
    gtk_combo_box_set_active(GTK_COMBO_BOX((GtkComboBox *)sosc.combo_resolution), 0);
}
#endif
void dealwith_ok(void)
{
    #ifdef __linux__
    set_old_mode();
    system("/usr/bin/feh --bg-scale /etc/xdg/openbox/wallpaper.jpg");
    gtk_widget_destroy(GTK_WIDGET(g_change_resolution_ask_window));
    #endif
}

void close_ask_window(void)
{
    #ifdef __linux__
    FILE *fp = fopen("/etc/X11/xinit/xinitrc.d/90-monitor.sh", "a+");
    if (NULL == fp)
    {
        printf("file open Fail!\n");
    }
    int res = system("chmod 777 /etc/X11/xinit/xinitrc.d/90-monitor.sh");
    if (res != 0)
    {
        M_DEBUG("chmod 777 error");
    }
    char ch = fgetc(fp);
    if (ch == EOF)
    {
        fputs("xrandr\n", fp);
    } else
    {
        char cmd[200];
        const char *vga = gtk_combo_box_text_get_active_text((GtkComboBoxText *)(sosc.combo_display_interface));
        sprintf(cmd, "sed -i '/%s --mode/d' /etc/X11/xinit/xinitrc.d/90-monitor.sh", vga);
        res = system(cmd);
    }
    fclose(fp);


    FILE *fp2 = fopen("/etc/X11/xinit/xinitrc.d/90-monitor.sh", "a+");
    if (NULL == fp2)
    {
        printf("file open Fail!\n");
    }
    fputs(g_scr_cmd, fp2);
    fputs("\n", fp2);
    fclose(fp2);

    gtk_widget_destroy(g_change_resolution_ask_window);
    #endif
}

void cb_change_resolution_buttonAsk(void)
{
    GtkWidget *grid, *hbox, *label_none, *label_none2, *label_none3, *label, *label2, *btn_yes, *btn_no;
    g_change_resolution_ask_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_keep_above(GTK_WINDOW(g_change_resolution_ask_window), TRUE);
    gtk_window_set_modal((GtkWindow *)g_change_resolution_ask_window, TRUE);
    gtk_window_set_position(GTK_WINDOW(g_change_resolution_ask_window), GTK_WIN_POS_CENTER_ALWAYS);//居中
    gtk_container_set_border_width(GTK_CONTAINER(g_change_resolution_ask_window), 35);
    gtk_window_set_decorated(GTK_WINDOW(g_change_resolution_ask_window), FALSE);//无边框

    grid       = gtk_grid_new();
    label      = gtk_label_new(NULL);
    label_none  = gtk_label_new("                           ");
    label_none2 = gtk_label_new("                           ");
    label_none3 = gtk_label_new(NULL);
    label2     = gtk_label_new("\n   是否要保留此显示设置？  \n");
    btn_yes     = gtk_button_new_with_label("还原");
    btn_no      = gtk_button_new_with_label("保留更改");

    gtk_button_set_relief(GTK_BUTTON(btn_no),  GTK_RELIEF_NONE);
    gtk_button_set_relief(GTK_BUTTON(btn_yes), GTK_RELIEF_NONE);

    gtk_widget_set_size_request(label, 70, 70);

    hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 10);
    gtk_container_add(GTK_CONTAINER(hbox), label_none);
    gtk_container_add(GTK_CONTAINER(hbox), label);
    gtk_container_add(GTK_CONTAINER(hbox), label_none2);

    gtk_grid_set_row_spacing((GtkGrid*)grid, 5);
    gtk_grid_set_column_spacing((GtkGrid*)grid, 10);

    gtk_grid_attach((GtkGrid *)grid, label_none3, 0, 0, 4, 1);
    gtk_grid_attach((GtkGrid *)grid, hbox,       0, 1, 4, 1);
    gtk_grid_attach((GtkGrid *)grid, label2,     1, 2, 2, 1);
    gtk_grid_attach((GtkGrid *)grid, btn_yes,     1, 3, 1, 1);
    gtk_grid_attach((GtkGrid *)grid, btn_no,      2, 3, 1, 1);

    gtk_container_add(GTK_CONTAINER(g_change_resolution_ask_window), grid);

    g_signal_connect_swapped(G_OBJECT(btn_yes), "clicked", G_CALLBACK(dealwith_ok), NULL);
    g_signal_connect_swapped(G_OBJECT(btn_no),  "clicked", G_CALLBACK(close_ask_window), NULL);

    /*            CSS                  */
    set_img(label, "label", "wenhao.png");
    set_css(btn_yes, "button{color: white;background: rgb(53, 126, 169);border: 1px solid rgb(40, 94, 142);border-radius: 0px}");
    set_css(btn_yes, "button:hover{border-radius: 0px;background: #3070a9}");
    set_css(btn_no,  "button{color: white;background: #5cb85c;border: 1px solid rgb(57, 132, 57);border-radius: 0px}");
    set_css(btn_no,  "button:hover{border-radius:0px;background: #449d44;}");
    set_css(g_change_resolution_ask_window, "window{border-radius:0px;background-color: rgb(245, 245, 245)}");
    /*            CSS                 */
    gtk_widget_show_all(g_change_resolution_ask_window);
    gtk_window_set_position( GTK_WINDOW(g_change_resolution_ask_window), GTK_WIN_POS_CENTER_ALWAYS);//居中
}

GtkWidget *gtk_sys_display_grid(void)
{
    GtkWidget *label_diplay_interface, *label_resolution;
    GtkWidget *btn_advance, *btn_save_model, *btn_add_mode, *btn_del_mode;
    GtkWidget *hboxmode_tab2;
    GtkWidget *fixed_vga;
    GtkWidget *label_none_screen_big, *label_none_screen_small;
    GtkWidget *grid_screen = gtk_grid_new();

    gtk_grid_set_row_spacing((GtkGrid*)grid_screen, 21);
    gtk_grid_set_column_spacing((GtkGrid*)grid_screen, 30);

    g_fixed_vga_none = gtk_fixed_new();
    fixed_vga        = gtk_fixed_new();

    hboxmode_tab2 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 16);
    label_diplay_interface = gtk_label_new("显示接口");
    label_resolution       = gtk_label_new("   分辨率");

    btn_advance = gtk_button_new_with_label("高级");
    gtk_button_set_relief(GTK_BUTTON(btn_advance), GTK_RELIEF_NONE);

    btn_add_mode  = gtk_button_new_with_label("添加");
    gtk_button_set_relief(GTK_BUTTON(btn_add_mode),  GTK_RELIEF_NONE);
    gtk_widget_set_size_request(btn_add_mode, 96, 20);

    btn_del_mode  = gtk_button_new_with_label("删除");
    gtk_button_set_relief(GTK_BUTTON(btn_del_mode),  GTK_RELIEF_NONE);
    gtk_widget_set_size_request(btn_del_mode, 96, 20);

    btn_save_model  = gtk_button_new_with_label("应用");
    gtk_button_set_relief(GTK_BUTTON(btn_save_model),  GTK_RELIEF_NONE);
    gtk_widget_set_size_request(btn_save_model, 96, 20);

    gtk_box_pack_start(GTK_BOX(hboxmode_tab2), btn_del_mode, FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(hboxmode_tab2), btn_add_mode, FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(hboxmode_tab2), btn_save_model, FALSE, FALSE, 0);

    label_none_screen_big   = gtk_label_new(" \n\n\n\n\n\n\n\n\n\n\n   ");
    label_none_screen_small = gtk_label_new("  ");
    gtk_fixed_put((GtkFixed *)g_fixed_vga_none, label_none_screen_big,   30,  26);
    gtk_fixed_put((GtkFixed *)g_fixed_vga_none, label_none_screen_small, 235, 92);
    gtk_widget_set_size_request(label_none_screen_big, 520, 20);

    sosc.combo_display_interface = gtk_combo_box_text_new();
    sosc.combo_resolution        = gtk_combo_box_text_new();
    gtk_widget_set_size_request(sosc.combo_resolution, 320, 20);
    gtk_widget_set_size_request(sosc.combo_display_interface, 320, 20);

    gtk_fixed_put((GtkFixed *)fixed_vga, label_diplay_interface,       94,  7);
    gtk_fixed_put((GtkFixed *)fixed_vga, sosc.combo_display_interface, 174, 0);
    gtk_fixed_put((GtkFixed *)fixed_vga, label_resolution,             94,  50);
    gtk_fixed_put((GtkFixed *)fixed_vga, sosc.combo_resolution,        174, 42);
    gtk_fixed_put((GtkFixed *)fixed_vga, btn_advance,                  0,   84);
    gtk_fixed_put((GtkFixed *)fixed_vga, hboxmode_tab2,                174, 84);

    gtk_grid_attach((GtkGrid *)grid_screen, g_fixed_vga_none, 0, 0, 5, 1);
    gtk_grid_attach((GtkGrid *)grid_screen, fixed_vga,     1, 3, 4, 4);

    g_signal_connect(G_OBJECT(sosc.combo_resolution), "changed", G_CALLBACK(change_screen_pic), label_none_screen_small);
    g_signal_connect(G_OBJECT(btn_advance), "clicked", G_CALLBACK(grade_init_dpms), NULL);
    g_signal_connect(G_OBJECT(btn_add_mode), "clicked", G_CALLBACK(add_mode_dialog), NULL);
    g_signal_connect(G_OBJECT(btn_del_mode), "clicked", G_CALLBACK(del_mode_dialog), NULL);
    g_signal_connect(G_OBJECT(btn_save_model), "clicked", G_CALLBACK(buttonsetsosc), NULL);

    set_css(label_none_screen_big, "label{color: white;background: rgb(220,220,220);border: none;border-radius: 0px}");
    set_css(label_none_screen_small, "label{color: white;background: rgb(53, 126, 169);border: none;border-radius: 0px}");
    set_css(btn_advance, "button{ color:white;"
            "background:#5cb85c;border:1px solid rgb(57,132,57);"
            "border-radius:0px}");
    set_css(btn_advance, "button:hover{border-radius:0px;background:#449d44;}");
    set_css(btn_save_model,   "button{ color:white;"
            "background:rgb(53,126,169);"
            "border:1px solid rgb(40,94,142);"
            "border-radius: 0px}");
    set_css(btn_save_model,   "button:hover{border-radius:0px;background: #3070a9}");
    set_css(btn_del_mode, "button{ color:white;"
            "background:rgb(53,126,169);"
            "border:1px solid rgb(40,94,142);"
            "border-radius:0px}");
    set_css(btn_del_mode, "button:hover{border-radius:0px;background: #3070a9}");
    set_css(btn_add_mode, "button{ color:white;"
            "background:rgb(53,126,169);"
            "border:1px solid rgb(40,94,142);"
            "border-radius:0px}");
    set_css(btn_add_mode, "button:hover{border-radius:0px;background: #3070a9}");

    return grid_screen;
}
